package com.qm.console.config.mybatisdb;

import com.qm.console.component.util.BeanUtil;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Arrays;

import javax.sql.DataSource;

/**
 * Created by Edison.hu on 18/9/13.
 */
@Configuration
@MapperScan(basePackages = {"com.qm.console.dao.dm", "com.qm.console.dao.mapper"},sqlSessionFactoryRef = "dmSqlSessionFactory")
public class DmDataSourceConfig {



    @Primary
    @Bean(name = "dmDataSourceProperties")
    @ConfigurationProperties("spring.datasource.dm")
    public DataSourceProperties masterDataSource(){
//        return DataSourceBuilder.create().build();
        return new DataSourceProperties();
    }

//    @Primary
    @Bean(name = "dmDataSource")
    public DataSource dataSource(@Qualifier("dmDataSourceProperties") DataSourceProperties properties) {
        return properties.initializeDataSourceBuilder().build();
    }



    @Bean(name = "dmSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dmDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        Resource[] dmResources = new PathMatchingResourcePatternResolver().getResources("classpath:com/qm/console/dao/dm/*.xml");
        Resource[] businessResources = new PathMatchingResourcePatternResolver().getResources("classpath:com/qm/console/dao/mapper/*.xml");
        sessionFactoryBean.setMapperLocations(
            ArrayUtils.addAll(dmResources, businessResources)
        );
        return sessionFactoryBean.getObject();
    }

    @Bean
    public JdbcTemplate jdbcTemplate() {
        DataSource dataSource = (DataSource) BeanUtil.getApplicationContext().getBean("dmDataSource");
        return new JdbcTemplate(dataSource);
    }

}

